package net.tavion.demo.chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import net.tavion.demo.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    static Logger logger=LoggerFactory.getLogger(ServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg) {
        ByteBuf in = (ByteBuf) msg;

        logger.info("receiver msg:{}",in.toString(CharsetUtil.UTF_8));

        ctx.write(createByteBuf( new  Random().nextInt()));
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){

        ctx.write(createByteBuf( ", hello,complete"));
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,  Throwable cause) {
        logger.error(cause.getMessage(),cause);
        ctx.close();
    }


    private <T> ByteBuf createByteBuf(T o){
        ByteBuf in2=Unpooled.buffer();
        String s=BeanUtils.writeAsString(o);
        in2.writeBytes(s.getBytes(CharsetUtil.UTF_8));
        return in2;
    }
}